import { EyeOutlined, DeleteOutlined } from '@ant-design/icons'
import { useBoolean } from '@gnlab/utils/env-react'
import { message, Popconfirm } from 'antd'
import { ReactComponent as WorkFlowIcon } from '@/desktop/assets/workflow.svg'
import ApplyRecords from '@/desktop/views/app-center/chat-flows/ApplyRecords'
import services from '@/services'
import type { BoundChatFlow } from '@/services/features/chat-flows'
import { ChatFlowBoundStatus, chatFlowBoundStatusTexts } from '@/services/features/chat-flows'
import { spin } from '..'
import BindChatFlow from './bind'
import './index.module.less'

export default function ChatFlow(props: {
  contactId: string
  forGroup: boolean
  className?: string
}) {
  const { contactId, forGroup, className } = props

  const [flow, setFlow] = useState<false | null | BoundChatFlow>(false) // 当前联系人绑定的 flow： false 加载中，null 未绑定
  const loadFlow = useCallback(async () => {
    const res = await services.features.chatFlows.getBoundFlow(contactId)
    if (res.success) setFlow(res.data)
    else {
      void message.error(`绑定工作流加载失败：${res.error}`)
      setFlow(null)
    }
  }, [contactId])
  useEffect(() => void loadFlow(), [loadFlow])

  const [binding, startBind, finishBind] = useBoolean(false)
  const handleFinishBind = useCallback(() => {
    finishBind()
    void loadFlow()
  }, [finishBind, loadFlow])

  const unbind = useCallback(async () => {
    const res = await services.features.chatFlows.unbind(contactId)
    if (!res.success) void message.error(`删除失败：${res.error}`)
    void loadFlow()
  }, [contactId, loadFlow])

  const [showingRecords, showRecords, closeRecords] = useBoolean(false)

  // =========================================

  const content =
    flow === false ? (
      spin
    ) : flow === null ? (
      <a onClick={startBind}>添加工作流</a>
    ) : (
      <div styleName="flow">
        <WorkFlowIcon />
        <div styleName="name">{flow.name}</div>
        <div styleName="status">{chatFlowBoundStatusTexts[flow.status]}</div>
        <div styleName="actions">
          <EyeOutlined styleName="show-records" onClick={showRecords} />

          <Popconfirm
            title={
              flow.status === ChatFlowBoundStatus.Applying
                ? '移除后，此工作流尚未执行的工作项目将不会被执行。确认移除？'
                : '确定移除此工作流吗？'
            }
            onConfirm={() => void unbind()}
          >
            <DeleteOutlined styleName="remove" />
          </Popconfirm>
        </div>
      </div>
    )

  return <>
    <section styleName="chat-flow" className={className}>
      <label>工作流</label>
      <div>{content}</div>
    </section>

    <BindChatFlow
      contactId={binding ? contactId : null}
      forGroup={forGroup}
      onFinish={handleFinishBind}
    />
    <ApplyRecords contactId={showingRecords ? contactId : null} onClose={closeRecords} />
  </>
}
